package com.zm.admin.zmeng.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zm.admin.zmeng.domain.ZmRole;
import com.zm.admin.zmeng.domain.ZmRoleMenu;
import com.zm.admin.zmeng.dto.UserDto;
import com.zm.admin.zmeng.mapper.ZmRoleMapper;
import com.zm.admin.zmeng.mapper.ZmRoleMenuMapper;
import com.zm.admin.zmeng.mapper.ZmUserRoleMapper;
import com.zm.admin.zmeng.service.ZmRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/***
 *
 * @Auther: MuYun
 * @Date: 2022/10/17 21:30
 * @Description： 权限service接口实现类
 *
 */
/**开启事务后，该类所有方法将被事务管理*/
@Service
@Transactional(rollbackFor = Exception.class)
public class ZmRoleServiceImpl implements ZmRoleService {

    @Resource
    private ZmRoleMapper zmRoleMapper;

    @Resource
    private ZmUserRoleMapper zmUserRoleMapper;

    @Resource
    private ZmRoleMenuMapper zmRoleMenuMapper;

    @Override
    public List<UserDto> selectUserAndOrgForRole(String id,Integer startIndex,Integer pageSize,String type) {
        List<UserDto> userDtoList =new ArrayList<>();
        //查询
        userDtoList = zmRoleMapper.selectUserAndOrgForRole(id,startIndex,pageSize,type);
        return userDtoList;
    }

    @Override
    public void cancel(List<UserDto> list) {
        //重置这些用户的权限
        zmUserRoleMapper.cancelUserRole(list);
    }

    @Override
    public void assign(String roleId, List<UserDto> list) {
        //修改这些用户的权限
        zmUserRoleMapper.updateUserRole(roleId,list);
    }

    @Override
    public void batchDel(List<ZmRole> list) {
        //在角色表中删除角色
        zmRoleMapper.batchDel(list);
        //重置角色对应用户的角色
        zmUserRoleMapper.resetUserRole(list);
    }

    @Override
    public void batchAdd(String id,List<String> list) {
        QueryWrapper<ZmRoleMenu> wrapper=new QueryWrapper<>();
        List<ZmRoleMenu> roleMenuList=new ArrayList<>();
        for (String str:list){
            ZmRoleMenu zmRoleMenu=new ZmRoleMenu();
            //zmRoleMenu.setId(UUID.randomUUID().toString());
            zmRoleMenu.setRoleId(id);
            zmRoleMenu.setMenuId(str);
            zmRoleMenu.setCreateTime(DateUtil.date());
            zmRoleMenu.setCreateBy("等待开发捏");
            if(StrUtil.isNotEmpty(id)){
                zmRoleMenu.setUpdateTime(DateUtil.date());
                zmRoleMenu.setUpdateBy("等待开发捏");
            }
            roleMenuList.add(zmRoleMenu);
        }

        //先删,这步只针对修改接口，新增接口因为角色是新的，所以角色菜单表里查不到数据不会影响，就没做判断
        zmRoleMenuMapper.delete(wrapper.lambda().eq(ZmRoleMenu::getRoleId,id));

        //如果对应菜单权限id数组非空
        if(ObjectUtil.isNotEmpty(list)){
            //再新增
            zmRoleMenuMapper.batchAdd(roleMenuList);
        }
    }
}
